如何在python中表示类的新部分?

2024-04-20 08:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

比如说我上过这样的课:

class Planet(object):
    def _init_(self, id = 0, name="", mass = 0)
    self.id = id
    self.name = name
    self.mass = mass

我能这样写地球吗-

import(whatever)
name=earth
id=1
mass = 5.97219 × 1024 kg

或者行星地球必须以与类相同的方式编写(对不起,我的格式不好,每个代码都合并到一个块中,而不是单独的块)?你知道吗


Tags: nameimportselfid地球objectinitdef
2条回答

您需要创建Planet的实例并对其进行初始化:

earth = Planet()
earth.name = "earth"
earth.id = id
earth.mass = 5.97219 × 1024 kg
class Planet(object):
    def _init_(self, id = 0, name="", mass = 0)
        self.id = id
        self.name = name
        self.mass = mass

earth = Planet(id=1,name="Earth",mass=5.97219*1024)
上课太好了!想象一下,你希望你的星球能够做些什么,可能是对其他星球。这个怎么样?你知道吗

class Planet(object):
    def __init__(self,id=0,name="",mass=0,population=0)
        self.id = id
        self.name = name
        self.mass = mass
        self.population = population
    def colonize(self,other,size = 1000):
        if not isinstance(other,Planet):
            raise TypeError("You can only colonize other celestial bodies!")
        if not isinstance(size,int):
            raise TypeError("You need a number of people to colonize with")
        self.population -= size
        other.population += size

mercury = Planet(1, "Mercury")
venus = Planet(2,"Venus")
earth = Planet(3,"Earth",5.97219*1024,7000000000)
mars = Planet(4,"Mars")

>>> earth.population
7000000000
>>> mars.population
0
>>> earth.colonize(mars)
>>> earth.population
6999999000
>>> mars.population
1000

相关问题 更多 >