封装步骤: 1.属性私有化,---》__name 2.设置set和get方法,--->set_name(),get_name() 3.添加安全条件判断,---》参数类型判断,取值范围判断 """ class Dog(object): def __init__(self, legnum): self.__legnum = legnum def set_legnum(self, legnum): if legnum < 0 or legnum > 4: print('无耻') return self.__legnum = legnum def get_legnum(self, str1): if str1 == 'ok': return self.__legnum else: print('答案不对,请重新输入') wangcai = Dog(4) print(wangcai._Dog__legnum)
""" 继承:子类继承父类的成员 子类可以直接调用父类中的属性和方法 """ class Person(object): def __init__(self, name): print('第二个重载的构造方法') self.name = name self.age = 20 pass def __add__(self, other): p = Person('') p.name = self.name + other.name return p def __mul__(self, other): p = Person('') p.name = self.name * other return p def __str__(self): return '{},{}'.format(self.name, self.age) def __len__(self): return len(self.name) per = Person('jack') per2 = Person('tom') print(per+per2) print((per.__mul__(2)))