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
Harwee
1,6502 gold badges22 silver badges35 bronze badges
1 Answer 1
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
Dunes
42.2k7 gold badges87 silver badges107 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
self.nameassignment.selfrefers the current object. Howself.nameis possible without creating an object?