[英]Pythonic way of converting parameters to the same standard within all methods of a class
[英]How do I give same methods to all of the variable in the class in clean pythonic way?
我想給類中的所有變量執行相同方法的能力,也就是說我有Dog類,方法為double和append
class Dog:
def __init__ (self, height, weight, age):
self.height = height
self.weight = weight
self.age = age
def double:
self.height = height * height
def append:
weight = list(weight).append(weight)
假設我想讓所有其他可變身高,體重和年齡也都可以加倍並附加自己。 現在,我可以這樣做,以便我可以一遍又一遍地針對每個可變的身高,體重,年齡等對同一方法進行修改。但是,對於每一遍,一遍又一遍地寫出相同的方法,這看起來並不干凈變量,如果說我說30個變量,並且需要為所有變量定義相同的方法,則更加荒謬。 什么是干凈的Pythonic方法? 我應該在班級里面放班嗎? 定義功能?
您可以為要操作的變量創建一個類。 例如:
class Parameter:
def __init__(self, value):
self.value = value
def double(self):
self.value = 2*value
def append(self):
self.value = list(value).append(value) # I'm not sure what is your intention with this.
然后像這樣使用它:
class Dog:
def __init__ (self, height, weight, age):
self.height = Parameter(height)
self.weight = Parameter(weight)
self.age = Parameter(age)
並且您訪問這樣的值:
dog = Dog(20, 30, 7)
dog.height.value
dog.height.double()
dog.height.append()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.