l信息量大。这篇文章演示了Python类的许多特性背后的“为什么”,包括 @ StistalPosie和 @ Cyrase> ,而不是Python,但应该帮助你考虑。啊,我记得我读的文章/帖子是用Python语言说话的……我强烈推荐Raymond Hett
l信息量大。这篇文章演示了Python类的许多特性背后的“为什么”,包括 @ StistalPosie和 @ Cyrase> ,而不是Python,但应该帮助你考虑。啊,我记得我读的文章/帖子是用Python语言说话的……我强烈推荐Raymond Hett,python,static-methods,Python,Static Methods,l信息量大。这篇文章演示了Python类的许多特性背后的“为什么”,包括 @ StistalPosie和 @ Cyrase> ,而不是Python,但应该帮助你考虑。啊,我记得我读的文章/帖子是用Python语言说话的……我强烈推荐Raymond Hettinger的46分钟PyCon 2013谈话。他是Python的核心开发人员之一,他的讲座总是既有趣又信息丰富。这一个演示了Python类的许多特性背后的“原因”,包括@staticmethod和@classmethod.Hmm。。如果我在这件
l信息量大。这篇文章演示了Python类的许多特性背后的“为什么”,包括<代码> @ StistalPosie和
@staticmethod
和@classmethod
.Hmm。。如果我在这件事上错了,请纠正我。。如果要使用staticmethod,是否需要使用self
,例如def get_carries(self)
?@dispidia-否,因为使用静态方法不需要实例化obj是的,我们不能在staticmethod内部使用自变量,幸运的是我们仍然可以使用类内部定义的属性,包括描述符。好的,我尝试了这两种方法——无论是否使用@staticmethod
,我的代码仍然有效。因此,我对是否应该使用它感到困惑。如果您希望能够在不创建类实例的情况下使用该方法,请向其添加@staticmethod
。如果没有,请不要。。如果我在这件事上错了,请纠正我。。如果要使用staticmethod,是否需要使用self
,例如def get_carries(self)
?@dispidia-否,因为使用静态方法不需要实例化obj是的,我们不能在staticmethod内部使用自变量,幸运的是我们仍然可以使用类内部定义的属性,包括描述符。好的,我尝试了这两种方法——无论是否使用@staticmethod
,我的代码仍然有效。因此,我对是否应该使用它感到困惑。如果您希望能够在不创建类实例的情况下使用该方法,请向其添加@staticmethod
。如果不是,代码< >类主窗口< /代码>不考虑作为基类吗?不,MainWindow只是一个客户端,它使用你的上下文实例。基类意味着它充当UR上下文的父级,并且您的上下文可以重用基类公共方法或声明。添加一些可运行的示例代码,希望能对您有所帮助。<代码>类主窗口< /代码>不被视为基类吗?不,MainWindow只是一个客户端,它使用您的上下文实例。基类意味着它充当您上下文的父类,您的上下文可以重用您的基类公共方法或声明。添加了一些可运行的示例代码,希望能对您有所帮助。
import util
class MainWindow(object):
...
def method_context_callback(self, *args):
if args[0] == 'M1':
self.ctx = utils.M1Context(...)
self.ctx.run_context()
elif args[1] == 'M2':
self.ctx = utils.M2Context(...)
self.ctx.run_context()
class M1Context(object):
def __init__(self):
...
def run_context(self):
# Do something when Method01 is used
class M2Context(object):
def __init__(self):
...
def run_context(self):
# Do something when Method02 is used
class Banana:
def __init__(self, age):
self.age = age
@staticmethod
def get_calories():
return 88.7
def get_age():
return self.age;
Banana.get_calories() # Is valid
Banana.get_age() # will not be valid
banana = Banana(age=2)
banana.get_age() # valid
banana.get_calories() # valid
from abc import ABCMeta, abstractmethod
class ContextBase(object):
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def run_context(self):
print 'this is logic inside of base'
@staticmethod
def step_a():
pass
@staticmethod
def step_b():
pass
class M1Context(ContextBase):
def __init__(self):
super(M1Context, self).__init__()
def run_context(self):
super(M1Context, self).run_context()
print 'logic inside of subclass'
super(M1Context, self).step_a()
super(M1Context, self).step_b()
m1 = M1Context()
m1.run_context()