[英]Is there a possibility in python to call a classmethod out of the constructor?
Is there a possibility in python to call a classmethod out of the constructor? python中是否有可能从构造函数中调用类方法?
I have a method in a class and want to call it while creating a new element. 我在一个类中有一个方法,想在创建新元素时调用它。
Is it possible? 可能吗?
def __init__(self, val1, val2):
if (val1 == 5) and (val2 == 2):
function5_2(self)
def function5_2(self):
(arguments)
Yes you can do it: 是的,您可以这样做:
class Foo(object):
def __init__(self, a):
self.a = a
self.cls_method()
@classmethod
def cls_method(cls):
print 'class %s' % cls.__name__
Output: 输出:
class Foo
Yes, it is. 是的。 Here is an example of a classmethod getting called from a constructor: 这是从构造函数调用类方法的示例:
class C(object):
def __init__(self):
C.func()
@classmethod
def func(cls):
print 'func() called'
C()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.