python3 类

class Robot:
    """Represents a robot, with a name."""    #这串string可以通过 Robot.__doc__ 调到

    # A class variable, counting the number of robots  这个类似类静态成员了,被整个类拥有
    population = 0

    def __init__(self, name):    #类似构造函数,当构造一个实例时隐式被调用
        """Initializes the data."""
        self.name = name         #self.xxx变量都是被实例拥有
        print("(Initializing {})".format(self.name))

        # When this person is created, the robot
        # adds to the population
        Robot.population += 1

    def die(self):
        """I am dying."""
        print("{} is being destroyed!".format(self.name))

        Robot.population -= 1           #静态成员直接通过类名调用,或者 self.__class__.population 调用

        if Robot.population == 0:
            print("{} was the last one.".format(self.name))
        else:
            print("There are still {:d} robots working.".format(
                Robot.population))

    def say_hi(self):
        """Greeting by the robot.

        Yeah, they can do that."""    # Robot.say_hi.__doc__
        print("Greetings, my masters call me {}.".format(self.name))

    @classmethod
    def how_many(cls):               # 类似静态成员函数,所以加上 @classmethod修饰
        """Prints the current population."""
        print("We have {:d} robots.".format(cls.population))


droid1 = Robot("R2-D2")
droid1.say_hi()
Robot.how_many()

droid2 = Robot("C-3PO")
droid2.say_hi()
Robot.how_many()

print("\nRobots can do some work here.\n")

print("Robots have finished their work. So let's destroy them.")
droid1.die()
droid2.die()

Robot.how_many()
class SchoolMember:
    '''Represents any school member.'''
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('(Initialized SchoolMember: {})'.format(self.name))

    def tell(self):
        '''Tell my details.'''
        print('Name:"{}" Age:"{}"'.format(self.name, self.age), end=" ")  #不让换行,因为子类可能会接着打印


class Teacher(SchoolMember):   #指定基类,放在元组中
    '''Represents a teacher.'''
    def __init__(self, name, age, salary):
        SchoolMember.__init__(self, name, age)  #这里需要我们主动调用构造函数,构造子类的基类部分
        self.salary = salary
        print('(Initialized Teacher: {})'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Salary: "{:d}"'.format(self.salary))


class Student(SchoolMember):
    '''Represents a student.'''
    def __init__(self, name, age, marks):
        SchoolMember.__init__(self, name, age)
        self.marks = marks
        print('(Initialized Student: {})'.format(self.name))

    def tell(self):
        SchoolMember.tell(self)
        print('Marks: "{:d}"'.format(self.marks))

t = Teacher('Mrs. Shrividya', 40, 30000)
s = Student('Swaroop', 25, 75)

# prints a blank line
print()

members = [t, s]  #python的list并不要求同类型
for member in members:
    # Works for both Teachers and Students
    member.tell()

 

你可能感兴趣的:(misc知识点)