首先,您的@method
班级结构是错误的。
当我运行您的代码时,它说:
class MyClass(GeneratedClass):
@classmethod
def do(self, a):
return a
class myCustomClass():
def func(self):
MyClass.do(a)
输出:
Traceback (most recent call last):
File "test.py", line 236, in <module>
class MyClass(GeneratedClass):
NameError: name 'GeneratedClass' is not defined
您的班级结构完全错误。如果要传递参数,请使用__init__
方法。
class MyClass:
def __init__(self, GeneratedClass):
self.generated_class = GeneratedClass
def do(self):
doSomething(self.generated_class)
class MyCustomClass:
def func(self):
GeneratedClass = 1
MyClass(GeneratedClass).do()
myCustomClass().func()
如果你正在使用@methodclass
你不应该通过self
,它是cls
。就像在这个例子中一样:
from datetime import date
# random Person
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthYear):
return cls(name, date.today().year - birthYear)
def display(self):
print(self.name + "'s age is: " + str(self.age))
person = Person('Adam', 19)
person.display()
person1 = Person.fromBirthYear('John', 1985)
person1.display()
如果您正在尝试继承,请以这个示例为例。
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def update(self, iterable):
for item in iterable:
self.items_list.append(item)
__update = update # private copy of original update() method
class MappingSubclass(Mapping):
def update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self.items_list.append(item)
现在根据您的要求合而为一:
class GeneratedClass:
def __init__(self):
self.myclass = self
def print(self):
print('hello_people')
class MyClass(GeneratedClass):
def __init__(self,a):
self.a = a
GeneratedClass.__init__(self)
print(a)
@classmethod
def give_param(cls, a):
return cls(a)
class myCustomClass:
def func(self):
MyClass.give_param('aa')
myCustomClass().func()
注意:我使用过python 3.x。