[英]Assign Python class variable with a method of that class
我有這樣的代碼:
def my_func():
pass
class MyClass():
class_variable = my_func()
pass
i = MyClass()
由於my_func
在邏輯上與MyClass
相關,並且在它之外沒有任何作用,所以我寧願有這樣的東西:
class MyClass():
class_variable = my_func()
def my_func():
pass
i = MyClass()
當然,上面的方法不起作用,因為在my_func
未定義它。 還有其他從類內部分配類變量的方法嗎?
我個人將my_func()
放在課堂之外 。 當然,它只能用於類定義,但是如果一旦定義了類就沒有用,則不應將其作為類API的一部分。
如果即使在類創建后仍應將my_func()
函數與該類一起使用,則仍可以使用MyClass.my_func()
作為靜態方法來使該類起作用。 在這種情況下限定第一設置類變量之前的函數:
class MyClass():
@staticmethod
def my_func():
pass
class_variable = my_func.__func__()
@staticmethod
方法不是嚴格必需的,因為在設置class_variable
, my_func
仍是類定義主體中的本地名稱。
但是,由於無論如何都將其用作靜態函數,因此也可以將其標記為靜態函數。 但是,優點是MyClass.my_func()
現在也可以使用。
因為@staticmethod
方法不會綁定到類或實例屬性上下文之外,所以您確實需要通過使用__func__
屬性訪問包裝函數來首先對其進行包裝。
演示:
>>> class MyClass():
... @staticmethod
... def my_func():
... return 'foobar'
... class_variable = my_func.__func__()
...
>>> MyClass.class_variable
'foobar'
>>> MyClass.my_func()
'foobar'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.