詹惠儿

2018-12-03   阅读量: 753

数据分析师 Python编程 Python数据分析

Python中类、对象和成员是什么?

扫码加入数据分析学习群

下面是一个简单的Python程序,它使用单个方法创建一个类。

# A simple example class

class Test:

# A sample method

def fun(self):

print("Hello")

# Driver code

obj = Test()

obj.fun()

正如我们在上面所看到的,我们使用class语句和类的名称创建一个新类。接下来是一个缩进的语句块,它构成了类的主体。在这种情况下,我们在类中定义了一个方法。

接下来,我们使用类的名称后跟一对括号创建此类的对象/实例。

  1. 类方法必须在方法定义中具有额外的第一个参数。当我们调用方法时,我们不给这个参数赋值,Python提供它
  2. 如果我们有一个不带参数的方法,那么我们仍然必须有一个参数 - 自我。在上面的简单示例中查看fun()。
  3. 这类似于C ++中的this指针和Java中的这个引用。

当我们将此对象的方法称为myobject.method(arg1,arg2)时,Python会自动将其转换为MyClass.method(myobject,arg1,arg2) - 这就是所有特殊的自我。

类和实例变量(或属性)
在Python中,实例变量是其值在构造函数或方法中使用self分配的变量。

类变量是其值在类中赋值的变量。

# Python program to show that the variables with a value

# assigned in class declaration, are class variables and

# variables inside methods and constructors are instance

# variables.

# Class for Computer Science Student

class CSStudent:

# Class Variable

stream = 'cse'

# The init method or constructor

def __init__(self, roll):

# Instance Variable

self.roll = roll

# Objects of CSStudent class

a = CSStudent(101)

b = CSStudent(102)

print(a.stream) # prints "cse"

print(b.stream) # prints "cse"

print(a.roll) # prints 101

# Class variables can be accessed using class

# name also

print(CSStudent.stream) # prints "cse"

我们也可以在普通方法中定义实例变量。

# Python program to show that we can create

# instance variables inside methods

# Class for Computer Science Student

class CSStudent:

# Class Variable

stream = 'cse'

# The init method or constructor

def __init__(self, roll):

# Instance Variable

self.roll = roll

# Adds an instance variable

def setAddress(self, address):

self.address = address

# Retrieves instance variable

def getAddress(self):

return self.address

# Driver Code

a = CSStudent(101)

a.setAddress("Noida, UP")

print(a.getAddress())

添加CDA认证专家【维克多阿涛】,微信号:【cdashijiazhuang】,提供数据分析指导及CDA考试秘籍。已助千人通过CDA数字化人才认证。欢迎交流,共同成长!
5.6893 1 4 关注作者 收藏

评论(0)


暂无数据

推荐课程

推荐帖子