ITS·黑客

【python】面向对象

2017-05-21  本文已影响1人  MJXH
class Student(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score
    def print_score(self):
        print('%s: %s' % (self.name, self.score))
bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart.print_score()
lisa.print_score()
class Dog:
    def init(self, legs, colour):
        self.legs = legs
        self.colour = colour
fido = Dog(4, "brown")
spot = Dog(3, "mostly yellow")

对一只狗来说:_init_就是第一次写了一些信息的出生证明,几斤重,在哪里出生等等
变量self就是它以后会成为的那条狗。而self.color 或者self.legs或self.xx就是它今后的改变会成为怎么样一只狗,黄色 3条腿或其他
关于Class中的变量和_init_函数中的变量的差别:

class MyClass(object):
     i = 123
     def _init_(self):
         self.i = 345
print(MyClass().i)
345
print(MyClass.i)
123
上一篇 下一篇

猜你喜欢

热点阅读