Object-Oriented Programming in Python

本文介绍了Python中的面向对象编程,包括类的定义、实例化、初始化方法`__init__()`以及类和实例变量。通过示例展示了如何创建和使用类,特别讨论了类变量和实例变量的差异,以及它们可能导致的错误。类变量在所有实例间共享,而实例变量则为每个实例所独有。文章还提醒读者注意类变量在特定情况下可能引发的意外共享行为。
摘要由CSDN通过智能技术生成

Object-Oriented Programming in Python

Class Definition

class MyClass:
    foo = 11
    def bar(self):
        return 'hello object'

MyClass.foo and MyClass.bar are valid attribute references, returning an integer and a function object, respectively

Class instantiation

class MyClass:
    foo = 11
    def bar(self):
        return 'hello object'

instant = MyClass()
instant.bar() # call bar function

However, Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:

class MyClass:
    foo = 11
    def __init__(self, a, b):
      self.foo1 = a
      self.foo2 = b
    def bar(self):
        return 'hello object'

instant = MyClass(2,4)
print(instant.foo1, instant.foo2) #2 4

Class and Instance Variables

Class variable shared by all instances

class MyClass:
    addMe = 1
    def __init__(self, a, b):
      self.foo1 = a
      self.foo2 = b
    def bar(self):
        return 'hello object'
    def add(self,x):
      self.addMe += x

a = MyClass(2,4)
b = MyClass(3,6)
print(a.addMe)
a.add(2)
print(a.addMe)
b.add(3)
print(a.addMe)
print(b.addMe)

#1
#3
#3
#4

But sometimes it may lead to mistakes.(why)

class MyClass:
    addMe = []
    def __init__(self, a, b):
      self.foo1 = a
      self.foo2 = b
    def bar(self):
        return 'hello object'
    def add(self,x):
      self.addMe.append(x)

a = MyClass(2,4)
b = MyClass(3,6)
print(a.addMe)
a.add(2)
print(a.addMe)
b.add(3)
print(a.addMe)

#[]
#[2]
#[2, 3]

Reference

[9. Classes](

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值