Class test:
a=10
b=20
Def c(self,a,b):
Return a+b
Print test.a
#10
Print test.b
#20
Print test.c(1,2)
#Error unbound method c()
Plz point out were I am going wrong I am beginner in terms of using classes
Sorry for the upper cases in my code .I had to type it out on my tiny mobile screen.
You have tried to access method inside class directly.
To call method inside class need to create instance of class
following programming will work
class Test:
a = 10 # class variable
b = 20 # class variable
def c(self,a,b):
return a+b
print Test.a
print Test.b
obj = Test()
print obj.c(1,2) #3
# class is lowercase
# class names are by convention uppercase (Test)
class Test:
# def is lowercase
def c(self, a, b):
# return is lowercase
return a + b
# Create a new instance of the Test class
test = Test()
print test.c(1, 2) # prints 3
Related
Here is a minimal example:
This works in both python 3.5 and 2.7:
class A(object):
def __init__(self, foo):
self._foo = foo
class B(A):
def __init__(self, foo):
A.__init__(self, foo=foo)
b = B(1)
Change line:
A.__init__(self, foo=foo)
to
A.__init__(self=self, foo=foo)
In python 3.5 works without problems, but in python 2.7 you will receive the following error:
Traceback (most recent call last):
File "self_key.py", line 9, in <module>
b = B(1)
File "self_key.py", line 7, in __init__
A.__init__(self=self, foo=foo)
TypeError: unbound method __init__() must be called with A instance as first argument (got nothing instead)
Is self as keyword argument forbidden in python 2.7 or is this a bug?
Update
I'm aware that python will use the first parameter of a bound function to pass the reference to the object from which has been called. I also know that the __init__ function expects that this parameter is an instance of the class. In this case A.__init__ is unbound so we must provide that parameter manually.
When I asked about self as keyword argument forbidden I'm speaking about self as "the first parameter of __init__", which is supposed to receive a reference of the object to initialize. The name of the variable itself doesn't matter. We can perfectly change the name to this:, for example:
class A(object):
def __init__(this, foo):
this._foo = foo
class B(A):
def __init__(self, foo):
A.__init__(this=self, foo=foo)
b = B(1)
And it will be the same.
My question is why when calling the function we can perfectly specify that parameter as a positional argument (A.__init__(self, foo=foo)) but when we try to pass it as a keyword argument (A.__init__(this=self, foo=foo)) python 2.7 throws an error.
Actually, you don't have to use self keyword unless you're consistent. Check out this example, where I changed self to test :
class funcs():
def init(test, a, b):
test.a=a
test.b=b
def plus(test):
c = test.a + test.b
print"%d + %d = %d" %(test.a, test.b, c)
def minus(test):
c = test.a - test.b
print"%d - %d = %d" %(test.a, test.b, c)
obj = funcs()
obj.init(10, 6)
obj.plus()
obj.minus()
You can try to mix those instance name, so it won't be named self.
class A(object):
def __init__(a_obj, foo):
a_obj._foo = foo
class B(A):
def __init__(self, test, foo):
A.__init__(self, a_obj=test, foo=foo) # here you pass object of class B and actually another object of class B
a = A(2)
b = B(a, 1)
Giving output:
A.__init__(self, a_obj=test, foo=foo)
TypeError: __init__() got multiple values for keyword argument 'a_obj'
I'm not sure what actually you want to accomplish by passing those object like this. In your code, self in class A and self in class B are not the same objects.
I suppose that here: A.__init__(self=self, foo=foo) you are doing something like A_instance=B_instance (self=self)
Always use self for the first argument to instance methods.
Source: Python Documentation
I have an enum like this
#enum.unique
class TransactionTypes(enum.IntEnum):
authorisation = 1
balance_adjustment = 2
chargeback = 3
auth_reversal = 4
Now i am assigning a variable with this enum like this
a = TransactionTypes
I want to check for the type of 'a' and do something if its an enum and something else, if its not an enum
I tried something like this
if type(a) == enum:
print "do enum related stuff"
else:
print "do something else"
The problem is it is not working fine.
Now i am assigning a variable with this enum like this
a = TransactionTypes
I hope you aren't, because what you just assigned to a is the entire enumeration, not one of its members (such as TransactionTypes.chargeback) If that is really what you wanted to do, then the correct test would be:
if issubclass(a, enum.Enum)
However, if you actually meant something like:
a = TransactionTypes.authorisation
then the test you need is:
# for any Enum member
if isinstance(a, Enum):
or
# for a TransactionTypes Enum
if isinstance(a, TransactionTypes):
reliable solution:
from enum import IntEnum
from collections import Iterable
def is_IntEnum(obj):
try:
return isinstance(obj, Iterable) and isinstance (next(iter(obj)), IntEnum)
except:
return False # Handle StopIteration, if obj has no elements
I thought I`ve got a ugly way. eg:
print(o.__class__.__class__)
Output:
<enum.EnumMeta>
as mentioned use isinstance method to check weather an instance is of enum.Enum type or not.
A small working code for demonstration of its usage:
import enum
class STATUS(enum.Enum):
FINISHED = enum.auto()
DELETED = enum.auto()
CANCELLED = enum.auto()
PENDING = enum.auto()
if __name__ == "__main__":
instance = STATUS.CANCELLED
if isinstance(instance, enum.Enum):
print('name : ', instance.name, ' value : ', instance.value)
else:
print(str(instance))
Output:
name : CANCELLED value : 3
There are already good answers here but in case of it might be useful for some people out there
I wanted to stretch the question a little further and created a simple example
to propose a humble solution to help caller function who does maybe little knowledge about Enum
solve problem of sending arguments to functions that take only Enum
as a parameter by proposing a converter just below the file that Enum was created.
from enum import Enum
from typing import Union
class Polygon(Enum):
triangle: 3
quadrilateral: 4
pentagon: 5
hexagon: 6
heptagon: 7
octagon: 8
nonagon: 9
decagon: 10
def display(polygon: Polygon):
print(f"{polygon.name} : {polygon.value} ")
def do_something_with_polygon(polygon: Polygon):
"""This one is not flexible cause it only accepts a Polygon Enum it does not convert"""
""" if parameter is really a Polygon Enum we are ready to do stuff or We get error """
display(polygon)
def do_something_with_polygon_more_flexible(maybe_polygon_maybe_not: Union[Polygon, int, str]):
""" it will be more convenient function by taking extra parameters and converting"""
if isinstance(maybe_polygon_maybe_not, Enum):
real_polygon = maybe_polygon_maybe_not
else:
real_polygon = get_enum_with_value(int(maybe_polygon_maybe_not), Polygon, Polygon.quadrilateral)
""" now we are ready to do stuff """
display(real_polygon)
def get_enum_with_value(key: int, enum_: any, default_value: Enum):
""" this function will convert int value to Enum that corresponds checking parameter key """
# create a dict with all values and name of Enum
dict_temp = {x.value: x for x in
enum_} # { 3 : Polygon.triangle , 4 :Polygon.quadrilateral , 5 : Polygon.pentagon , ... }
# if key exists for example 6 or '6' that comes to do_something_with_polygon_more_flexible
# returns Polygon.hexagon
enum_value = dict_temp.get(key, None)
# if key does not exist we get None
if not enum_value:
... # if key does not exist we return default value (Polygon.quadrilateral)
enum_value = default_value # Polygon.quadrilateral
return enum_value
I'm getting this error:
unbound method hello() must be called with A instance as first argument(got nothing instead)
import B
class A():
#staticmethod
def newHello():
A.oldHello() # Here the error
print ' world'
def inject(self):
A.oldHello = B.hello
B.hello = A.newHello
A().inject()
B.hello()
B.py contain only a function "hello" that print "hello"
def hello():
print 'hello'
Thanks in advance
A.oldhello() is not static. So in B's hello function is referencing A's nonstatic oldhello statically. A does in fact need an instance. I'm not too good with the decorators and how they work but maybe try declaring oldhello in the class before the function and calling it #staticmethod. I don't know if the staticness carries over if you override the method.
Try this:
class B():
def hello(self):
print "hello"
class A():
#staticmethod
def newHello(self):
A.oldHello(self) # Here the error
print ' world'
def inject(self):
A.oldHello = B.hello
B.hello = A.newHello
A().inject()
B().hello()
Possible duplicates:
Is there a way to create subclasses on-the-fly?
Dynamically creating classes - Python
I would like to create a subclass where the only difference is some class variable, but I would like everything else to stay the same. I need to do this dynamically, because I only know the class variable value at run time.
Here is some example code so far. I would like FooBase.foo_var to be "default" but FooBar.foo_var to be "bar." No attempt so far has been successful.
class FooBase(object):
foo_var = "default"
def __init__(self, name="anon"):
self.name = name
def speak(self):
print self.name, "reporting for duty"
print "my foovar is '" + FooBase.foo_var + "'"
if __name__ == "__main__":
#FooBase.foo_var = "foo"
f = FooBase()
f.speak()
foobarname = "bar"
#FooBar = type("FooBar", (FooBase,), {'foo_var': "bar"})
class FooBar(FooBase): pass
FooBar.foo_var = "bar"
fb = FooBar()
fb.speak()
Many thanks
EDIT so I obviously have a problem with this line:
print "my foovar is '" + FooBase.foo_var + "'"
The accepted answer has self.foo_var in the code. That's what I should be doing. I feel ridiculous now.
What about this:
def make_class(value):
class Foo(object):
foo_var = value
def speak(self):
print self.foo_var
return Foo
FooBar = make_class("bar")
FooQux = make_class("qux")
FooBar().speak()
FooQux().speak()
That said, can't you make the value of foo_var be a instance variable of your class? So that the same class instantiated with different input behaves in different ways, instead of creating a different class for each of those different behaviours.
Facing the error as :
AttributeError: 'function' object has no attribute 'd'.
how to access the dictionary?
code:
class A:
#staticmethod
def test():
d = {}
d['a'] = 'b'
print d
#staticmethod
def test1():
d1 = {}
d1['a'] = 'c'
if (A.test.d['a'] == A.test1.d1['a']):
print "yes"
else:
print "Oh No!!"
A.test()
A.test1()
Check out this on the matter of static variables in Python.
You should be able to sort it out using A.d and A.d1 whenever you wish to use the static variables. Note that, as you have them, they are local to test and test1, respectively. If you want them to be static, you have to declare them inside the class scope, but not within any function definition.