[英]Python add a variable to a class
I am trying to understand python classes:我想了解 python 类:
I have the following case:我有以下情况:
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
I would like to define a variable c
and store it in the child
class.我想定义一个变量c
并将其存储在child
class 中。 Is it suitable to do this?这样做合适吗? Should I define an __init__
method to create the variable?我应该定义一个__init__
方法来创建变量吗?
Best regards此致
Yes, you can/should definitely have __init__
in the derived classes.是的,你可以/应该在派生类中有__init__
。 You just need to initialize the base class via super
method.您只需要通过super
方法初始化基础 class 即可。 Here is the example according to your case.这是根据您的情况的示例。
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)
If your base class requires some parameters, you can do it like this如果你的基础 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)
Do you want your variable to change?你想让你的变量改变吗? You can simply put c
inside your new child class, such as a static class variable (have a look here maybe).您可以简单地将c
放在您的新孩子 class 中,例如 static ZA2F2ED4F8 DCEBC2CBBD4C21A
class child(parent):
c = 3
You can access it doing:您可以通过以下方式访问它:
child.c
If you want to pass by the __init__()
function and define the new variable when you define the class, use the super()
method as @Ahmad Anis was suggested.如果您想通过__init__()
function 并在定义 class 时定义新变量,请使用super()
方法,因为建议使用@Ahmad Anis 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.