6.1
class Thing:
pass
example = Thing()
Thing
main.Thing
example
<main.Thing at 0x7f4878f5ff28>
6.2
class Thing2:
letters = 'abc'
Thing2.letters
‘abc’
6.3
class Thing3:
def __init__(self):
self.letters = 'xyz'
thing = Thing3()
thing.letters
‘xyz’
6.4
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol= symbol
self.number = number
obj1 = Element('Hydrogen', 'H', 1)
e1_dict = {
'name': 'Hydrogen',
'symbol':'H',
'number':1,
}
hydrogen = Element(e1_dict['name'], e1_dict['symbol'], e1_dict['number'])
hydrogen.name
‘Hydrogen’
hydrogen2 = Element(**e1_dict)
hydrogen2.name
‘Hydrogen’
6.6
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol= symbol
self.number = number
def dump(self):
print(f'{self.name}-{self.symbol}-{self.number}')
hydrogen = Element('이름', '심볼', 10)
hydrogen.dump()
이름-심볼-10
6.7
print(hydrogen)
<main.Element object at 0x7f4878558160>
class Element:
def __init__(self, name, symbol, number):
self.name = name
self.symbol= symbol
self.number = number
def __str__(self):
return f'{self.name}-{self.symbol}-{self.number}'
hydrogen = Element('이름', '심볼', 1)
print(hydrogen)
이름-심볼-1
6.8
class Element:
def __init__(self, name, symbol, number):
self.__name = name
self.__symbol= symbol
self.__number = number
def __str__(self):
return f'{self.name}-{self.symbol}-{self.number}'
@property
def name(self):
return self.__name
@property
def symbol(self):
return self.__symbol
@property
def number(self):
return self.__number
hydrogen = Element('이름', '심볼', 10)
hydrogen.name
‘이름’
6.9
class Bear():
def __init__(self):
pass
def eat(self):
return f'berries ({type(self).__name__})'
class Rabbit():
def __init__(self):
pass
def eat(self):
return f'clover ({type(self).__name__})'
class Octothorpe:
def __init__(self):
pass
def eat(self):
return f'campers ({type(self).__name__})'
def print_eat(instance):
print(instance.eat())
bear = Bear()
rabbit = Rabbit()
octothorpe = Octothorpe()
print_eat(bear)
print_eat(rabbit)
print_eat(octothorpe)
berries (Bear) clover (Rabbit) campers (Octothorpe)
6.10
class Laser:
def __init__(self):
pass
def does(self):
return f'disintegrate ({type(self).__name__})'
class Claw:
def __init__(self):
pass
def does(self):
return f'crush ({type(self).__name__})'
class SmartPhone:
def __init__(self):
pass
def does(self):
return f'ring ({type(self).__name__})'
class Robot:
def __init__(self, laser, claw, smartphone):
self.laser = laser
self.claw = claw
self.smartphone = smartphone
def does(self):
print(self.laser.does(), self.claw.does(), self.smartphone.does())
robot = Robot(Laser(), Claw(), SmartPhone())
robot.does()
disintegrate (Laser) crush (Claw) ring (SmartPhone)
Comments