I have the following class, where I want to use the method location_change within __init__for that class. Is there a way to do this? The example I use below is a simplification but what I need to do is use a class method to transform some constructor data. Can this be done in python?
class dummy:
def __init__(self):
self.location = 'USA'
print(self.location)
location_change()
print(self.location)
def location_change():
self.location = 'UK'
first_dummy = dummy()
-
3It's better to name classes in CamelCase.demalexx– demalexx2012年01月17日 14:17:46 +00:00Commented Jan 17, 2012 at 14:17
-
2There seems to be some confusion between classmethods and methods on classes; sadly, these are different.Katriel– Katriel2012年01月17日 14:26:09 +00:00Commented Jan 17, 2012 at 14:26
3 Answers 3
Sure it can!
self.location_change()
each method in a class should take at least one argument and that is conventionally called self.
def location_change(self):
an introductory tutorial on oop in python http://www.voidspace.org.uk/python/articles/OOP.shtml
the documentation http://docs.python.org/tutorial/classes.html
Comments
Try this
class Dummy:
def __init__(self):
self.location = 'USA'
print(self.location)
self.location_change()
print(self.location)
def location_change(self):
self.location = 'UK'
first_dummy = Dummy()
Comments
class Dummy:
def __init__(self):
self.location = 'USA'
print(self.location)
Dummy.location_change(self)
print(self.location)
def location_change(self):
self.location = 'UK'
first_dummy = Dummy()
print(first_dummy)
What you needed to do was tell "location_change" that it was working with argument, self. Otherwise it's an undefined variable. You also needed to use the class name when calling it. This should give you:
USA
UK
<__main__.Dummy object at 0x1005ae1d0>
1 Comment
dummy.location_change(self) instead of self.location_change()? This way if a sub-class implement location_change that implementation will not be used!