class Animal:
__count=0
def __init__(self,name):
self.name=name
Animal.__count+=1
@classmethod
def get_count(self):
return self.__count
dog=Animal('liu')
print(dog.get_count())
cat=Animal('wang')
print(cat.get_count())
__count=0
def __init__(self,name):
self.name=name
Animal.__count+=1
@classmethod
def get_count(self):
return self.__count
dog=Animal('liu')
print(dog.get_count())
cat=Animal('wang')
print(cat.get_count())
2022-02-11
最贊回答 / weixin_慕用0068683
如果count改成__count變成類的私有屬性后,在__init__方法里無法直接__count訪問類的私有屬性,需要Animal.__count,嘗試了下self.__count也可以,我理解是__count本身是類的屬性,任何一個實例并不單獨具有這個屬性,但是可以通過實例調用類的get和set方法去修改類的屬性,就和直接用類名調用get和set方法效果是一樣的,比如下面的代碼里animal.set和dog.set都可以修改類的屬性__count。<...code...>
2022-02-11
最贊回答 / 慕函數7599421
假如<...code...>你可以推算def gcd(a, b)的過程(類似于for循環),得到兩個數的最大公約數為3,這個3會在最終的結果中作為分母被除掉。沒有沒有def gcd(a, b)函數,那么我們得到的最終結果會有3/6,4/8這樣的結果。
2022-01-24
def f(x):
return x.title
for item in map(f, ['alice', 'BOB', 'CanDY']):
print(item)
return x.title
for item in map(f, ['alice', 'BOB', 'CanDY']):
print(item)
2022-01-10
最贊回答 / weixin_慕設計1349666
class Animal():? ? def __init__(self,name,age,location):? ? ? ? self.__name=name? ? ? ? self.__age=age? ? ? ? self.__location=location? ? def get_info(self):? ? ? ? return 'name={},\nage={},\nlocation={}'.format(self.__name,self.__age,self.__location)? ? ...
2022-01-07
Traceback (most recent call last):
File "index.py", line 27, in
print(r1 / r2)
TypeError: unsupported operand type(s) for /: 'Rational' and 'Rational'
本節的代碼運行錯誤,提示地板除的那一行報錯,/沒有定義,把__truediv__改成__div__運行正確
File "index.py", line 27, in
print(r1 / r2)
TypeError: unsupported operand type(s) for /: 'Rational' and 'Rational'
本節的代碼運行錯誤,提示地板除的那一行報錯,/沒有定義,把__truediv__改成__div__運行正確
2022-01-06