如何将类本身初始化为类Object

时间:2015-11-11 12:47:35

标签: python python-2.7 class

如何将类初始化为具有相同名称的对象

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

此处a是一个对象,因此我可以a.name("Hello")

但我想要实现test.name("Hello")而不做test = test()

之类的事情

1 个答案:

答案 0 :(得分:2)

简单的回答是不要打扰&#34; setter&#34;功能。只需直接访问该属性即可。例如

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"

如果函数执行的操作比设置属性稍微复杂一些,那么可以将其设为classmethod。例如

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"