第八章第1-2讲:python之对象

第1讲:魔法——对象

1.对象出发点:是提高编程的效率,解决重复的劳动,人性懒惰的使然。

2.对象包含2个方面:

 属性:如何描述对象

 方法:对该像能做什么?

 对象=属性+方法

第2讲:创建对象

1. 类:对象

 类:具有相同属性和方法的集合(好比户型图)

 对象:讲抽象实现为显示的存在(根据户型图实现的一个个相同的布局格局的房子)

 2.定义类:

    class Classname:

  属性

  方法

3.创建类与实例化对象

class Person:
    def setName(self,name):
        self.name = name
    def getName(self):
        return self.name
    def greet(self):
        return "hello! I'm %s" % self.name
foo = Person()
bar = Person()
foo.setName("Bela")
bar.setName("Leo")
print(foo.greet())
print(bar.greet())
print(foo)
print(Person)

案例说明:

1.class关键字申明类,class后紧跟类名(类名一般首字母大写Person);class Person(object)object是代表从那个类里继承

2.Person类包含了3个方法(不是函数)

3.self参数是对于对象自身的引用,其也是方法与函数的区别

4.foo=Person()实例化

5.bar.setName("Bela")实例方法

6.print(foo) 结果<__main__.Person object at 0x0034E9D0>,foo指向了Person的实例(内存)

4.初始化__init__()
注意:初始化__init__
     init前后是各2个下划线
     当类使用了初始化方法,对象在实例化时,必须将init中的参数一并赋予
class Person:
    def __init__(self,name):
        self.name = name
    # def setName(self,name):
    #     self.name = name
    def getName(self):
        return self.name
foo = Person("Bela")
print(foo)
# 对象=属性+方法
class Myclass:
    # 属性:
    i = 12345
    def f(self):
        return "hello world!"
x = Myclass()
print("MyClass类的属性为:",x.i)
print("MyClass类的属性为:",x.f())
class Person:
    def __init__(self,name):
        self.name = name
    def greet(self):
        return "hello,I'm %s." % self.name
foo = Person("Bela")
print(foo.greet())
print(Person.greet(foo))
class Person:
    i = 12345
    def greet(self):
        print('hello world!')
foo = Person()
print(foo.__init__())
print(foo.__str__()) # 内在的方法
print(foo)

结果:
None
<__main__.Person object at 0x011CDE70>
<__main__.Person object at 0x011CDE70>


猜你喜欢

转载自www.cnblogs.com/ling07/p/11223706.html