簡體   English   中英

有什么方法可以在python中創建類時初始化屬性/屬性?

[英]Any way to initialize attributes/properties during class creation in python?

與Python中的這一行代碼等效嗎?

// C# just shows how class looks like
class MyClass {
    public int A {get; set;}
    public int B {get; set;}
}

// This is that one-line code in C#. Any pythonic way to do something like this?
// var x = MyClass() { A=1, B=2 } - "var" syntax sugar, at compile time it's == MyClass
MyClass x = MyClass() { A=1, B=2 }

編輯:也許我的問題不是那么精確。 我的主要目標是不將參數傳遞給構造函數。

如何初始化許多類成員(它們的任何組合),而不將它們傳遞給構造函數以及沒有帶有所有默認值的構造函數。

編輯:Thx的答案,對不起困惑的問題。 我只是想知道有關主題的問題的答案-什么是初始化類的屬性子集而無需在構造函數中顯式編寫它們的最佳方法(pythonic方法)。

實際上,我不了解C#,但查看您的代碼,我認為這是您正在查看的代碼。

def MyClass (object):
    def __init__ (A, B):
        self.A = A
        self.B = B

x = MyClass(A=1, B=2)

編輯:

如果要查找100個參數,請使用**kwargs類的東西。

我不確定您要實現的目標,但是您可能希望將通用參數傳遞給類構造函數,例如:

class MyClass:
    def __init__(self, **kwargs):
        for key in kwargs:
            setattr(self, key, kwargs[key])

x = MyClass(a='test', b='test2')
# x.a == 'test'
# x.b == 'test2'
y = MyClass(c=123, d='something else')
# y.c = 123
# y.d = 'something else'

要在Python中創建一個類,只需執行以下操作:

class Name:
    def __init__(self, arg1): # When an instance of a class is made this will be executed.
        self.var1 = 1
        self.var2 = 2
        self.arg1 = arg1

person1 = Name("arg1") # Create instance of the class

我個人不知道是否有一種方法可以用Python一行完成此操作,因為您還需要創建init()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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