Privatization and processing class

Coding _ * _ #: _ * _. 8 UTF- 
# @time: 2020/1/16 22:18
# @author: Dery
# @file: class_private.py
# @Software: PyCharm


# privatization
# package: 1 Private 2. the definition of public property part of the set \ get method
# __ attribute: that is to privatize property, access is limited to the class
' ''
privatization
1. hidden attribute, the outside world will not be free to modify
2 can also be modified, by way to do
DEF setXXX (Self, xxx):
1. screening assignment of content
if xxx eligibility:
assignment
else:
not assigned
3. If you want to get a specific attribute, use the get method completes
def get (self, xxx) :
return self.xxx

'' '


class Student:
# # 18 is a class attribute __age =
DEF the __init __ (Self, name, Age):
Self .__ name = name
Age Age .__ = Self
Self .__ Score = 59

# define the public set / get method
# set for assignment, get to the value

DEF set_age (Self, Age):
IF 0 <Age <= 120:
Self .__ = Age Age
the else:
( 'not within the age range!') Print

DEF set_name (Self, name):
IF len (name) == 6:
Self .__ name = name
the else:
( '! name instead of six') Print

DEF get_age (Self):
# Self .__ Age = Age
return Self .__ Age

DEF __str __ (Self):
return 'name: {}, Age: {}, test scores: {}'. the format (Self .__ name, Self .__ Age, Self .__ score)


zhangsan = Student ( 'Joe Smith 11111111', 90)
# zhangsan.set_name ( 'yupengnihao ')
Print (zhangsan.get_age ())
Print (zhangsan)
# Print (dir (Student))
# Print (dir (zhangsan))

# _*_ coding:utf-8 _*_
# @Time :2020/1/16 23:00
# @Author :dery
# @File :private_handle.py
# @Software :PyCharm


class Student:
# __age = 18 # 类属性
def __init__(self, name, age):
self.name = name
self.__age = age

@property
def age(self):
return self.__age

@age.setter
def age(self, age):
if 0 < age <= 120:
self.__age = age
else:
print('年龄不在范围内!')

# def get_age(self):
# # self.__age = age
# return self.__age

def __str__(self):
return 'Name: {}, Age: {}'. the format (the self.name, Self .__ Age)


S = Student ( 'zhangsna', 30)

# privatization assignment
Print (s.age)
Print (the dir (S))

Guess you like

Origin www.cnblogs.com/python-beginner/p/12203757.html