I am creating a subclass, but I am having difficulties making it inherit from the parent class:
def ParentClass(object):
def __init__(self,num):
self.num = num
self.get_soup()
def get_soup(self):
self.soup = 'soup'
return self.soup
def SubClass(Advert):
def __init__(self,num):
ParentClass.__init__(self,num)
def test(self):
print 'it works'
print self.num
if __name__== "__main__":
num = 1118868465
ad = SubClass(num)
ad.test()
Should I have a look at metaclasses?
You have functions in your code not classes, the parent class is also called ParentClass not Advert:
class ParentClass(object): # class not def
def __init__(self,num):
self.num = num
self.get_soup()
def get_soup(self):
self.soup = 'soup'
return self.soup
class SubClass(ParentClass): # inherit from ParentClass
def __init__(self, num):
super(SubClass, self).__init__(num)
def test(self):
print 'it works'
print self.num
You might want to have a read of this tutorial
Related
class Main:
def __init__(self):
self.number = 10
class Sub1(Main):
def __init__(self):
super().__init__()
def addnum(self):
self.number += 1
print(self.number)
class Sub2(Main):
def __init__(self):
super().__init__()
def func(self):
print(self.number)
sub2 = Sub2()
sub1 = Sub1()
sub1.addnum()
sub2.func()
In class Main, attribute number=10 is created
In class Sub1, function addnum increases number by 1
In class Sub2, function func prints the number, it prints 10, how do I make it print 11?
So how can changes to an attribute in a class be activated in another class?
So you want number to be shared across Main, Sub1, and Sub2, so that if an instance of Sub1 modifies number instances of Main and Sub2 can access that new number. You really don't want to do this, if you need to share variables across classes you're better off using a container that all those classes can access. For example:
class Container:
number = 10
class Main:
def __init__(self):
self.container = Container()
def set_number(self, new_num):
self.container.number = new_num
class New:
def __init__(self, main):
self.container = main.container
def addone(self):
self.container.number += 1
main = Main()
new = New(main)
new.addone()
print(main.container.number) # 11
main.set_number(1000)
print(new.container.number) # 1000
This is just a much cleaner and easier approach.
class base():
def __init__(self):
self.var = 10
def add(self, num):
res = self.var+num
return res
class inherit(base):
def __init__(self, num=10):
x = super().add(num)
a = inherit()
print(a)
Hello,
I'm learning about inheritance and super(). When running this, the error AttributeError: 'inherit' object has no attribute 'var' is returned. How can I inherit the init variables too?
You first need to call super constructor because you did not define var in your base class constructor.
Working version of your code (though you should probably add var in base __init__)
class Base:
def __init__(self):
self.var = 10
def add(self, num):
res = self.var + num
return res
class Inherit(Base):
def __init__(self, num=10):
super().__init__()
x = super().add(num)
a = Inherit()
print(a)
one possible solution
class Base:
def __init__(self, var=10):
self.var = var
def add(self, num):
res = self.var + num
return res
class Inherit(Base):
pass
a = Inherit()
a.add(0) # replace 0 with any integer
Say I have a class "NumberStore"
class NumberStore(object):
def __init__(self, num):
self.num = num
def get(self):
return self.num
And later on, for the purpose of serialization, I want to print a definition of the class, either exactly as stated, or equivalently stated. Is there any way in python to access a class's definition as in the idealized example below?
>>> NumberStore.print_class_definition()
"class NumberStore(object):\n def __init__(self, num):\n self.num = num\n \n def get(self):\n return self.num"
Yep, with inspect.getsource:
from inspect import getsource
class NumberStore(object):
def __init__(self, num):
self.num = num
def get(self):
return self.num
#classmethod
def print_class_definition(cls):
return getsource(cls)
Use inspect.getsource.
import inspect
source_text = inspect.getsource(NumberStore)
I would like a method in a base class to call another method in the same class instead of the overriding method in an inherited class.
I would like the following code to print out
Class B: 6
Class A: 9
Can this be done?
# Base class definition
class ClassA(object):
def __init__(self):
print("Initializing A")
# hoping that this function is called by this class's printFnX
def fnX(self, x):
return x**2
def printFnX(self, x):
print("ClassA:",self.fnX(x))
# Inherits from ClassA above
class ClassB(ClassA):
def __init__(self):
print("initizlizing B")
def fnX(self, x):
return 2*x
def printFnX(self, x):
print("ClassB:", self.fnX(x))
ClassA.printFnX(self,x)
bx = ClassB()
bx.printFnX(3)
Congratulations, you've discovered the motivating use case for Python's double-underscore name mangling :-)
For the details and a worked-out example see: http://docs.python.org/tutorial/classes.html#private-variables and at http://docs.python.org/reference/expressions.html#atom-identifiers .
Here's how to use it for your example:
# Base class definition
class ClassA(object):
def __init__(self):
print("Initializing A")
# hoping that this function is called by this class's printFnX
def fnX(self, x):
return x**2
__fnX = fnX
def printFnX(self, x):
print("ClassA:",self.__fnX(x))
# Inherits from ClassA above
class ClassB(ClassA):
def __init__(self):
print("initizlizing B")
def fnX(self, x):
return 2*x
def printFnX(self, x):
print("ClassB:", self.fnX(x))
ClassA.printFnX(self,x)
bx = ClassB()
bx.printFnX(3)
The use case is described as a way of implementing the Open-Closed Principle in "The Art of Subclassing" found at http://www.youtube.com/watch?v=yrboy25WKGo&noredirect=1 .
The same can be achieved by making fnX and printFnX both classmethods.
class ClassA(object):
def __init__(self):
print("Initializing A")
# hoping that this function is called by this class's printFnX
#classmethod
def fnX(self, x):
return x ** 2
#classmethod
def printFnX(self, x):
print("ClassA:",self.fnX(x))
class ClassB(ClassA):
def __init__(self):
print("initizlizing B")
def fnX(self, x):
return 2*x
def printFnX(self, x):
print("ClassB:", self.fnX(x))
ClassA.printFnX(x)
bx = ClassB()<br>
bx.printFnX(3)
How do I call method .get_item(Example1()).do_something() in class Base from inside the class Example2?
class Base:
items = []
def add_item(self, item):
self.items.append(item)
def get_item(self, item):
return self.items[0]
class Item:
pass
class Example1(Item):
def do_something(self):
print('do_something()')
class Example2(Item):
def __init__(self):
'''
How call this method .get_item(Example1()).do_something() ?
'''
if __name__ == '__main__':
base = Base()
base.add_item(Example1())
base.add_item(Example2())
If you want such functionality, you need to pass Base to Example2 guy:
class Example2(Item):
def __init__(self, base):
self.base = base
self.base.get_item(Example1()).do_something()
# or if don't want to store base, and just call its method once:
base.get_item(Example1()).do_something()
if __name__ == '__main__':
base = Base()
base.add_item(Example1())
base.add_item(Example2(), base)
self.get_item(...)
or
Base.get_item(self, ...)