簡體   English   中英

Python 將變量添加到 class

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM