26 类

使用type()判断对象类型

type(123)
<class ‘int’>

type(123)==int
True

使用isinstance()判断class的类型
继承关系是:object -> Animal -> Dog -> Husky

a = Animal()
d = Dog()
h = Husky()
isinstance(h, Husky)
True

isinstance(h, Husky)
True

isinstance(h, Animal)
True

self.name 在类外部可以访问;
self.__age 只能在类内部可以访问,类外包无法访问。

class person(object):
   def __init__(self,name,age):
        self.name=name
        self.__age=age

   def run(self):
        print(self.name+' is running.')

   def getAge(self):
       return self.__age

   def setAge(self,age):
       self.__age=age

a=person('Bao',19)
a.run()
a.setAge(36)
print(a.name)
print(a.getAge())

使用类中的全局变量: 类.变量名, 如 Student.count

class Student(object):
    count = 0

    def __init__(self, name):
        Student.count=Student.count +1
        self.name = name

方法twice通过传入类

class Animal(object):
    def run(self):
        print('animal is running.')

class Dog(Animal):
    def run(self):
        print('Dog is running.')

class Cat(Animal):
    def __init__(self,name):
        self.name=name

def twice(Animal):
    Animal.run()
    Animal.run()
a=Animal()
d=Dog()
c=Cat('CC') 
twice(d)

使用dir查看一个对象的所有属性和方法

dir(c)
输出:['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'run']

getattr()、setattr()以及hasattr()

print(hasattr(c,'name'))
print(getattr(c,'name'))
setattr(c,'name','DD')
print(getattr(c,'name'))
输出:
True
CC
DD

使用@property、@***.setter 对参数进行检查

class tree(object):
    @property
    def height(self):
        return self._height

    @height.setter
    def height(self,value):
        if not isinstance(value,int):
            raise ValueError('not int')
        self._height=value

t=tree()
t.height=65
print(t.height)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值