Harwee
Harwee

Reputation: 1650

How to initialise class itself as class Object

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()

Upvotes: 1

Views: 74

Answers (1)

Dunes
Dunes

Reputation: 40903

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"

Upvotes: 3

Related Questions