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
运行下面一段就成功
class Animal: pass
dog = Animal()
cat = Animal()
dog.name = 'xiaohong'
dog.age = 13
cat.name = 'xiaohong2'
cat.age = 14
print(dog.name)
print(dog.age)
print(cat.name)
print(cat.age)
class Animal: pass
dog = Animal()
cat = Animal()
dog.name = 'xiaohong'
dog.age = 13
cat.name = 'xiaohong2'
cat.age = 14
print(dog.name)
print(dog.age)
print(cat.name)
print(cat.age)
2021-12-16