1

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()
Wooble
90.6k12 gold badges111 silver badges132 bronze badges
asked Jan 17, 2012 at 14:14
2
  • 3
    It's better to name classes in CamelCase. Commented Jan 17, 2012 at 14:17
  • 2
    There seems to be some confusion between classmethods and methods on classes; sadly, these are different. Commented Jan 17, 2012 at 14:26

3 Answers 3

5

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

answered Jan 17, 2012 at 14:16
Sign up to request clarification or add additional context in comments.

Comments

3

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()
S.Lott
393k83 gold badges521 silver badges791 bronze badges
answered Jan 17, 2012 at 14:15

Comments

1
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>
S.Lott
393k83 gold badges521 silver badges791 bronze badges
answered Jan 17, 2012 at 14:19

1 Comment

Why would you call dummy.location_change(self) instead of self.location_change()? This way if a sub-class implement location_change that implementation will not be used!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.