[英]Call class method from another class without inheritance and global in python
[英]Call method from another class without inheritance and creating an instance
假設我有一個使用方法_build_record
的 class Person
,我不希望用戶調用此方法或可以使用dir(Person)
看到此方法。
因此,我創建了另一個 class helper
並按原樣移動方法_build_record
,然后通過helper._build_record(self)
在Person
class 中調用它,它工作正常,但我不確定這是否是正確的方法或者是否有任何更好的方法。
這只是我正在做的一個例子,我的主要 class 有很多方法。
class helper(object):
"""Helper class for Person."""
def _build_record(self):
return { 'name': self.name, 'age': self.age }
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
self.record = helper._build_record(self)
a = Person('Saad', 100)
print(a.record)
_build_record(self)
self
的 self 應該是它的類自己的實例。 但它期待一些其他類的實例,所以這一切看起來都令人困惑。
Python 提供了兩種方法來調用 class 的方法而不創建實例: classmethod
和staticmethod
。
您的示例看起來像是staticmethod
的一個很好的用例。
class helper(object):
@staticmethod
def _build_record(person):
return { 'name': person.name, 'age': person.age }
現在更清楚_build_record
需要一個人實例。
更新:
如果您想訪問 class (以便您可以調用它的其他方法),您應該使用classmethod
。 類方法將接收當前的classmethod
作為第一個參數。
class helper(object):
@classmethod
def _build_record(cls, person):
# now you can call other methods of the class
cls.some_other_method()
return ...
classmethod
和staticmethod
以相同的方式調用。
如果您有雙下划線作為其前綴,則可以將其設為私有方法。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __build_record(self):
return { 'name': self.name, 'age': self.age }
a = Person('Saad', 100)
print(a.__build_record)
如果您嘗試調用該方法,您將看到錯誤
AttributeError: 'Person' object has no attribute '__build_record'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.