栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Object-Oriented Programming in Python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Object-Oriented Programming in Python

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](

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980224.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号