1

How to initialise class as an object with same name

>>> class test:
 def name(self,name_):
 self.name = name_
>>> a= test()
>>> a
<__main__.test instance at 0x027036C0>
>>> test
<class __main__.test at 0x0271CDC0>

here a is an object so I can do a.name("Hello")

But what I want to achieve is test.name("Hello") without doing something like test = test()

asked Nov 11, 2015 at 12:47
4
  • 1
    then you need to define name as classmethod. And also it won't support self.name assignment. Commented Nov 11, 2015 at 12:48
  • 4
    you realize that the first time you call the name method, you are effectively replacing the method with a string right? Commented Nov 11, 2015 at 12:49
  • 2
    self refers the current object. How self.name is possible without creating an object? Commented Nov 11, 2015 at 12:51
  • @JamesKent I didn't realise that, thanks Commented Nov 11, 2015 at 12:53

1 Answer 1

3

The simple answer is don't bother with a "setter" function. Just access the attribute directly. eg.

a = test()
a.name = "setting an instance attribute"
test.name = "setting the class attribute"
b = test()
# b has no name yet, so it defaults the to class attribute
assert b.name == "setting the class attribute"

If the function is doing something a little more complicated than just setting an attribute then you can make it a classmethod. eg.

class Test(object):
 # you are using python 2.x -- make sure your classes inherit from object
 # Secondly, it's very good practice to use CamelCase for your class names.
 # Note how the class name is highlighted in cyan in this code snippet.
 @classmethod
 def set_name(cls, name):
 cls.name = name
Test.set_name("hello")
assert Test().name == "hello"
answered Nov 11, 2015 at 15:59
Sign up to request clarification or add additional context in comments.

Comments

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.