因此,在我的职业生涯中,我一直致力于用 Python 替换 PHP。所以我在 apache 中将 WebPy 与 WSGI 一起使用,并且一切正常,但我仍在学习这门语言,并且找不到对此的简单解释。因此,在四处乱逛,试图让其他类的方法在其他类中工作时,我遇到了一些说明,这些说明显示第一个类被实例化,并在类名后附加了 (object)。事实证明这是有效的,让我可以将数据传递给另一个类(class)。谁能告诉我为什么这段代码会起作用?
关于工作,我的意思是,在我看来,如果第一个类在其定义期间未指定 (object),那么就无法将数据传递到该类中?这样对吗?
class MyClass(object):
def function1(self, num1, num2):
return num1 + num2
class index:
def GET(self):
form = web.input()
num1 = form.number1
num2 = form.number2
MyClass.function1(num1, num2)
我真的很想了解这一点。我的意思是我让它工作真是太好了(这是一个代码示例,而不是我的实际项目),但如果我理解它为什么工作,它会有所帮助。谢谢,我确定这可能是一个简单的问题。
最佳答案
Python 2 中有两种类型的类:旧式和新式。新样式类是通过子类化 object
创建的。区别不是那么大,事实上你几乎不会注意到它,如果你不使用多重继承和类型比较type
,即
class old_style:
def __init__(self):
pass
class new_style(object):
def __init__(self):
pass
old_style_instance1 = old_style()
old_style_instance2 = old_style()
new_style_instance1 = new_style()
new_style_instance2 = new_style()
type(old_style_instance1) == type(old_style_instance2)
返回False
type(new_style_instance1) == type(new_style_instance2)
返回 True
关于您的代码。您倾向于使用实例方法,就像它们是类方法一样,即方法 MyClass.function1
和 index.GET
有一个名为 self
的参数,因此它们只能从类实例中调用,而不能从类本身调用。 self
是在实例初始化时通过特殊方法(__new__
)创建的特殊命名空间,例如myclass_instance = MyClass()
。如果您想使用可以从类中调用的类方法或静态方法,您应该以不同的方式声明它们。
class MyClass(object):
@staticmethod
def function1(num1, num2):
return num1 + num2
class index:
@staticmethod
def GET():
num1, num2 = get_numbers_somehow()
MyClass.function1(num1, num2)
在这种情况下,代码将起作用,这与从 object
类继承的 MyClass
无关。您应该考虑阅读有关 Python 类和实例的内容以了解其中的区别。顺便说一句,@
语法用于装饰。如果您打算经常使用 Python 装饰器,请阅读它。
关于python - 为什么我需要将对象传递给此类才能使其工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30167380/