码迷,mamicode.com
首页 > 编程语言 > 详细

Python面向对象之封装

时间:2016-07-01 11:36:43      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

类class
继承(单继承、多继承)

类方法@classmethod修饰
实例方法def fn(self)
静态方法@staticmethod修饰

 

代码区:

class people:
    # 定义基本属性
    name=‘‘;
    age=0;

    # 定义私有属性,类的外部无法访问
    __weight=0;

    def __init__(self, n, a, w):
        self.name = n;
        self.age=a;
        self.weight=w;

    def speak(self):
        print(%s is %s years old.%(self.name, self.age));

p = people(dog, 8);
p.speak();

class people:
    # 共有变量
    name=jack;
    age=12;

p = people();
# 直接访问共有变量
print(p.name);
print(p.age);

class people2:
    #私有变量
    __name=jack;
    __age=12;

p2 = people2();
# 私有变量外部不可访问
print(p2.name); # 访问会报错

# 通过内部方法访问私有属性
class people:
    __name=jack;
    __age=12;

    def getName(self):
        return self.__name;

    def getAge(self):
        return self.__age;

p = people();
print(p.getName(), p.getAge());

# 实例属性可以不定义在class里
class people:
    age=12;

p = people();
p.name = jack;
print(p.name, p.age);
print(people.age);
print(people.name); # 会报错

# 内置的构造方法定义属性
class people:
    name=jack;
    
    def __init__(self, age):
        self.age = age;

p = people(12);
print(p.age);
print(people.age); # 会报错

class people:
    country=china;

print(people.country); # china
people.country = Japan;
print(people.country); # Japan

p = people();
print(p.country); # Japan

del p.country; # 删除实例属性
print(p.country); # 会报错

class people:
    country=china;

    # 类方法,用classmethod来修饰
    @classmethod
    def getCountry(cls):
        return cls.country;

p = people();
print(p.getCountry()); # china

class people:
    country=china;

    # 实例方法
    def getCountry(self):
        return self.country;

# 实例化类
p = people();
print(p.getCountry());

# 静态方法
class people:
    country=china;

    # 静态方法
    # 静态方法不用传self参数
    @staticmethod
    def getCountry():
        # 直接用类名调用变量
        return people.country;

# 不用实例化即可直接打印静态方法
print(people.getCountry());

 

Python面向对象之封装

标签:

原文地址:http://www.cnblogs.com/lqcdsns/p/5632407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!