Python Object-oriented

Source: Internet
Author: User

Python object-oriented 1, class definition
#定义类class Emp:  pass
2. Static variables
class Emp:    #静态变量,通过类直接访问    id = 100        #__开头的是私有属性    __age = 20#通过类直接访问print Emp.id
3. Constructors and instance methods

A fixed constructor name is the __init__ method.

class Emp:    #实例方法    def add(self , a, b):        return a + b         #构造函数    def __init__(self , name ,age):        #实例变量        self.name = name        self.age = age
4. destructor
class Emp:    #析构函数    def __del__(self):        print "销毁对象!"#创建对象e = Emp()#销毁对象e = None#删除对象的成员del e.name#删除变量del e
5. Built-in properties
#内置属性判断print hasattr(e , "age")print hasattr(e , "name")print getattr(e , "age")setattr(e , "age" , 40)print getattr(e , "age")print getattr(e , "name" , "nobody")delattr(e, "age")print hasattr(e , "age")#访问类的属性#__dict__访问类的成员d = Emp.__dict__print  d#访问类名print Emp.__name__#所有父类构成的元组print Emp.__bases__
6. Multiple inheritance
class Horse:    #__开头的方法时私有方法    def __run(self):        print "runing~~~"    def eat(self):        print "eating..."    def __init__(self , name):        self.name = nameclass Donkey:    money = 100    def __init__(self ,age):        self.age = age#多重继承class Luozi(Horse , Donkey):    def eat(self):        print "WWWWWWWWWWW"    def __init__(self):        #显式调用父类构造函数        Horse.__init__(self , "tom")        Donkey.__init__(self ,12)l1 = Luozi()print l1.eat()

Python Object-oriented

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.