i'm doing an UNO game using Pygame, i'm doing it with lists of cards and classes of each color, when I tried to test the inheritance for using the color class, I got this error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
x=example()
File "C:/Users/Tamara/Desktop/TEC/UNO/UNOclases.py", line 93, in __init__
Red.__init__(self,Redlist)
TypeError: unbound method __init__() must be called with Red instance as first argument (got example instance instead)
Here's the code (don't mind if one of the names is wrong written, I had to translate it from spanish):
class Red:
def setSpecialRedCards(self):
self.__Redlist.append(self.__steal2)
self.__Redlist.append(self.__steal2)
self.__Redlist.append(self.__Reverse)
self.__Redlist.append(self.__Reverse)
self.__Redlist.append(self.__Jump)
self.__Redlist.append(self.__Jump)
def setRedNumers (self, number,counter):
while counter<=9:
if numero!=0:
self.__Redlist.append(number)
self.__Redlist.append(number)
else:
self.__listaRoja.append(number)
number+=1
counter+=1
def getRed(self):
return self.__Redlist
def __init__(self, Redlist=[]):
self.__Redlist=Redlist
self.__number0 = "red 0"
self.__steal2 = "steal2"
self.__Reverse = "Reverse"
self.__jump = "jump"
class example:
def __init__(self, Redlist=[]):
Red.__init__(self,Redlist)
def example2(self):
return Red.__number0
Thank you for your help!
Your class example doesn't inherit from class Red.
Write
class example(Red):
....
Related
i am working with
inheritence,here i got output for single inheritence but multiple inheritence showing error.so please help me.I don't have any knowledge about mro in python.please give me good advice.
class Player:
def __init__(self,name,country):
self.name=name
self.country=country
def info(self):
return self.name+":"+self.country
class Ipl(Player):
def __init__(self,name,country,team):
Player.__init__(self,name,country)
self.team=team
def info_ipl(self):
return self.info()+"\nIpl team:"+self.team
x=Ipl("Suresh Raina","India","csk")
print(x.info_ipl())
class Carrier:
def ___init__(self,wicket,run):
self.wicket=wicket
self.run=run
def disp(self):
return "Wickets:"+self.wicket+"Runs:"+self.run
class Aauction(Ipl, Carrier):
def __init__(self,wicket,run,name,country,team):
Ipl.__init__(self,name,country,team)
Carrier.__init__(self,wicket,run)
self.Innings=Innings
def stati(self):
return self.info_ipl()+","+self.disp()+"Total Innings:"
x = Aauction(150,2000,"Suresh_Raina","India","kkr")
print(x.stati())
Above code giving following Error:-
Suresh Raina:India
Ipl team:csk
Traceback (most recent call last):
File "C:\Users\Rahul\Desktop\PYTHON\EXP8.py", line 49, in <module>
x = Aauction(150,2000,"Suresh_Raina","India","kkr")
File "C:\Users\Rahul\Desktop\PYTHON\EXP8.py", line 40, in __init__
Carrier.__init__(self,wicket,run)
TypeError: object.__init__() takes no parameters
Thank you.
I think the problem is that your __init__ has three underscores instead of two:
class Carrier:
def ___init__(self,wicket,run):
self.wicket=wicket
self.run=run
def disp(self):
return "Wickets:"+self.wicket+"Runs:"+self.run
should be:
class Carrier:
def __init__(self,wicket,run):
self.wicket=wicket
self.run=run
def disp(self):
return "Wickets:"+self.wicket+"Runs:"+self.run
class Car:
# constructor
def __init__(self, make, model, year, mpg):
# instance variables
self.carMake = make
self.carModel=model
self.carYear = year
self.efficiency=mpg
self.gas = 0
# special method
def __str__(self):
return "%s %s %s"%(self.carYear, self.carMake, self.carModel)
def refuel(self,gallon):
if gallon < 0:
print("Sorry, amount cannot be negative")
else:
self.gas=self.gas+gallon
print (self.gas)
print("Added %.2f gallon of gas to the tank"%(self.gas))
def gas(self):
print(self.gas)
> Traceback (most recent call last): File "<pyshell#12>", line 1, in
> <module>
> c1.gas() TypeError: 'int' object is not callable
Your method gas and your instance attribute gas created in __init__ have the same name. The method is stored on the class, but is "shadowed" by the attribute stored on the instance, since Python first looks for names on the instance, then on the class and its parents.
So self.gas is an integer and you can't call it.
You have self.gas initialized to an int in the __init__() method, but then you define a method named gas() as well. Once __init__() runs, self.gas is an int. I'm guessing somewhere you are calling gas() on an instance of this class.
Rename your gas() method to something like print_gas(), or, wherever you're calling this, instead of doing c1.gas(), just do print c1.gas.
Consider this class Test in a file called test.py:
class Test:
def __init__(self):
self.x=3
def x(self):
print self.x
Now I import class Test in my console and see what methods it has:
>>> from test import Test
>>> [method for method in dir(Test) if callable(getattr(Test, method))]
['__init__', 'x']
Notice that it has the method x. Now let's create an instance of Test
>>> k=Test()
Let's see what methods we have
>>> [method for method in dir(k) if callable(getattr(k, method))]
['__init__']
>>>
As you can see the method x is no longer available. why?
When you created k as an instance of Test, it executes the __init__ method and sees self.x=3 which redefines x to be just a variable in self and your method x() is gone. So when you do k.x() it thinks that you are doing it on self.x that you set in __init__ which is not callable. However just k.x will work as I show below:
>>> k.x()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> k.x
3
>>>
The conclusion is don't name your variables and methods the same.
I'm new to python and was working on this code:
class Shape:
def __init__(self, shape):
self.shape = shape
def shapeName(self):
print(self.shape)
class Rectangle(Shape): # Rectangle class inherits Shape
count = 0 # static variable
def __init__(self, name):
Shape.__init__(self.name)
print('In Rectangle')
Rectangle.count = Rectangle.count + 1
rec1 = Rectangle('Rectangle')
rec2 = Rectangle('Rectangle')
rec1.shapeName()
rec2.shapeName()
print( Rectangle.count )
I'm getting the following error:
C:\Python32\python.exe C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py
Traceback (most recent call last):
File "C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py", line 17, in <module>
rec = Rectangle('Rectangle')
File "C:/Users/ashutosh/PycharmProjects/Test/InheritanceTest.py", line 13, in __init__
Shape.__init__(name)
TypeError: __init__() takes exactly 2 arguments (1 given)
Process finished with exit code 1
The first argument to constructor is the current object and second is the name of the shape. Then why it is saying that I have to pass 2 arguments?
Shape is a class, not an object, so when you call Shape.__init__ there's no self variable. In other words, there is no instance of Shape to call init on. The instance you want is the subclass instance of Shape that you have, i.e. self (the Rectangle). You could simply pass self, like this:
Shape.__init__(self, name)
or make use of the super keyword:
super(Rectangle, self).__init__(name)
The super keyword allows you to implicitly refer to your superclass, without using the name.
In Python 3.0 you can simply write super().__init__(name) without even the child reference.
You have to pass self explicitly to Shape.__init__.
So your rectangle class should look like this:
class Rectangle(Shape): # Rectangle class inherits Shape
count = 0
def __init__(self, name):
Shape.__init__(self, name)
print('In Rectangle')
So I am having some trouble with inheritance in python. I have two classes. The first is
class Base1DHeatEquation:
def __init__(self, alpha, final_time, time_discrete):
self.alpha = alpha
self.final_time = final_time
self.time_discrete = time_discrete
#Additional Functions which aren't causing a problem
and the second is a class which inherits the first
class IntialValueTest1DHE(Base1DHeatEquation):
def __init__(self, alpha, final_time, time_discrete,intialValues,\
x_discrete ,noise):
super(IntialValueTest1DHE,self).__init__(self, alpha, final_time, time_discrete)
self.intialValues = intialValues
#Additional Functions which aren't causing a problem
The problem is when I trying to create an IntialValueTest1DHE object, I get the following
>>> import HeatEquation1D as he #The File where both classes are stored
>>> temp = he.IntialValueTest1DHE(1,1,100,np.sin,100,0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() takes exactly 4 arguments (7 given)
It seems like object creation is trying to access the init from the parent class in stead of the child class and I am not sure how to fix that.
You don't need to add "self" to super() declaration. Also, you should use "new style" classes:
class Base1DHeatEquation(object):
def __init__(self, alpha, final_time, time_discrete):
self.alpha = alpha
self.final_time = final_time
self.time_discrete = time_discrete
class IntialValueTest1DHE(Base1DHeatEquation):
def __init__(self, alpha, final_time, time_discrete,intialValues,
x_discrete ,noise):
super(IntialValueTest1DHE,self).__init__(alpha, final_time, time_discrete)
self.intialValues = intialValues
So I've looked at similar questions, and I've found some solutions to this, but I can't quite figure out how to do this.
What I'm trying to do is add a method to a class from a string. I can do this with the setattr() method, but that won't let me use self as an attribute in the extra method. Here's an example: (and I apologize for the variable names, I always use yolo when I'm mocking up an idea)
class what:
def __init__(self):
s = 'def yolo(self):\n\tself.extra = "Hello"\n\tprint self.extra'
exec(s)
setattr(self,"yolo",yolo)
what().yolo()
returns this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: yolo() takes exactly 1 argument (0 given)
and if s = 'def yolo():\n\tself.extra = "Hello"\n\tprint self.extra'
then I get this result:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in yolo
NameError: global name 'self' is not defined
This essentially means that I cannot dynamically create methods for classes, which I know is bad practice and unpythonic, because the methods would be unable to access the variables that the rest of the class has access to.
I appreciate any help.
You have to bind your function to the class instance to turn it into a method. It can be done by wrapping it in types.MethodType:
import types
class what:
def __init__(self):
s = 'def yolo(self):\n\tself.extra = "Hello"\n\tprint self.extra'
exec(s)
self.yolo = types.MethodType(yolo, self)
what().yolo()
On a side note, why do you even need exec in this case? You can just as well write
import types
class what:
def __init__(self):
def yolo(self):
self.extra = "Hello"
print self.extra
self.yolo = types.MethodType(yolo, self)
what().yolo()
Edit: for the sake of completeness, one might prefer a solution through the descriptor protocol:
class what:
def __init__(self):
def yolo(self):
self.extra = "Hello"
print self.extra
self.yolo = yolo.__get__(self)
what().yolo()
Another way, seems more elegant to me:
class what:
pass
ld = {}
exec("""
def yolo(self):
self.extra = "Hello"
print(self.extra)
""", None, ld)
# print('locals got: {}'.format(ld))
for name, value in ld.items():
setattr(what, name, value)
what().yolo()