[英]Python add a variable to a class
我想了解 python 类:
我有以下情况:
class parent:
def __init__(self):
self.a = 1
self.b = 2
def printFoo(self):
print(self.a)
class child(parent):
def createC(self, val): # Create a variable inside the derived class?
self.c = val
def printFoo(self): # overloaded function
print(self.c)
a = parent()
b = child()
b.createC(3)
b.printFoo()
# Edited:
# I can even create variables as: child.d = 10
我想定义一个变量c
并将其存储在child
class 中。 这样做合适吗? 我应该定义一个__init__
方法来创建变量吗?
此致
是的,你可以/应该在派生类中有__init__
。 您只需要通过super
方法初始化基础 class 即可。 这是根据您的情况的示例。
class parent:
def __init__(self):
self.a = 1
self.b = 2
def printFoo(self):
print(self.a)
class child(parent):
def __init__(self):
super().__init__() # initialize base class, pass any parameters to base here if it requires any
self.c = someval
# def createC(self, val): dont need these
# self.c = val
def printFoo(self): # overloaded function
print(self.c)
如果你的基础 class 需要一些参数,你可以这样做
class parent:
def __init__(self, a, b):
self.a = a
self.b = b
def printFoo(self):
print(self.a)
class child(parent):
def __init__(self, a, b, someval):
super().__init__(a, b) # initialize base class, pass any parameters to base here if it requires any
self.c = someval
#def createC(self, val): dont need these
# self.c = val
def printFoo(self): # overloaded function
print(self.c)
你想让你的变量改变吗? 您可以简单地将c
放在您的新孩子 class 中,例如 static ZA2F2ED4F8 DCEBC2CBBD4C21A
class child(parent):
c = 3
您可以通过以下方式访问它:
child.c
如果您想通过__init__()
function 并在定义 class 时定义新变量,请使用super()
方法,因为建议使用@Ahmad Anis 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.