Reputation: 107
For example say I had a class like this:
class Planet(object):
def _init_(self, id = 0, name="", mass = 0)
self.id = id
self.name = name
self.mass = mass
Can I write the planet earth like this -
import(whatever)
name=earth
id=1
mass = 5.97219 × 1024 kg
or must planet earth be written in the same way the class does (sorry for my bad formatting, the code for each is combined into one block not separate ones)?
Upvotes: 0
Views: 141
Reputation: 54193
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)
Classes are great! Imagine you want your planet to be able to do something, possibly to other planets. How about this?
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
Upvotes: 0
Reputation: 7380
You need to create an instance of Planet
and initialize it:
earth = Planet()
earth.name = "earth"
earth.id = id
earth.mass = 5.97219 × 1024 kg
Upvotes: 1