Python 언어 학습 (5) (대상 을 대상 으로 하 는 기초 & 진급, 정수 비교 와 내장 목록)
13242 단어 python 학습
class Student(object):
# __init__
# name age
def __init__(self, name, age):
self.name = name
self.age = age
def study(self, course_name):
print('%s %s.' % (self.name, course_name))
# PEP 8
# ( )
def watch_movie(self):
if self.age < 18:
print('%s 《 》.' % self.name)
else:
print('%s .' % self.name)
def main():
#
stu1 = Student(' ', 38)
# study
stu1.study('Python ')
# watch_av
stu1.watch_movie()
stu2 = Student(' ', 15)
stu2.study(' ')
stu2.watch_movie()
if __name__ == '__main__':
main()
class Test:
def __init__(self, foo):
self.__foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
def main():
test = Test('hello')
# AttributeError: 'Test' object has no attribute '__bar'
test.__bar()
# AttributeError: 'Test' object has no attribute '__foo'
print(test.__foo)
if __name__ == "__main__":
main()
class Test:
def __init__(self, foo):
self.__foo = foo
def __bar(self):
print(self.__foo)
print('__bar')
def main():
test = Test('hello')
test._Test__bar()
print(test._Test__foo)
if __name__ == "__main__":
main()
대상 을 향 해 승급
class Person(object):
def __init__(self, name, age):
self._name = name
self._age = age
# - getter
@property
def name(self):
return self._name
# - getter
@property
def age(self):
return self._age
# - setter
@age.setter
def age(self, age):
self._age = age
def play(self):
if self._age <= 16:
print('%s .' % self._name)
else:
print('%s .' % self._name)
def main():
person = Person(' ', 12)
person.play()
person.age = 22
person.play()
# person.name = ' ' # AttributeError: can't set attribute
if __name__ == '__main__':
main()
class Person(object):
# Person _name, _age _gender
__slots__ = ('_name', '_age', '_gender')
def main():
person = Person(' ', 22)
person._gender = ' '
# AttributeError: 'Person' object has no attribute '_is_gay'
# person._is_gay = True
from math import sqrt
class Triangle(object):
def __init__(self, a, b, c):
self._a = a
self._b = b
self._c = c
@staticmethod #
def is_valid(a, b, c):
return a + b > c and b + c > a and a + c > b
def perimeter(self):
return self._a + self._b + self._c
def area(self):
half = self.perimeter() / 2
return sqrt(half * (half - self._a) *
(half - self._b) * (half - self._c))
def main():
a, b, c = 3, 4, 5
#
if Triangle.is_valid(a, b, c):
t = Triangle(a, b, c)
print(t.perimeter())
#
# print(Triangle.perimeter(t))
print(t.area())
# print(Triangle.area(t))
else:
print(' .')
if __name__ == '__main__':
main()
from time import time, localtime, sleep
class Clock(object):
""" """
def __init__(self, hour=0, minute=0, second=0):
self._hour = hour
self._minute = minute
self._second = second
@classmethod #
def now(cls):
ctime = localtime(time())
return cls(ctime.tm_hour, ctime.tm_min, ctime.tm_sec)
def run(self):
""" """
self._second += 1
if self._second == 60:
self._second = 0
self._minute += 1
if self._minute == 60:
self._minute = 0
self._hour += 1
if self._hour == 24:
self._hour = 0
def show(self):
""" """
return '%02d:%02d:%02d' % \
(self._hour, self._minute, self._second)
def main():
#
clock = Clock.now()
while True:
print(clock.show())
sleep(1)
clock.run()
if __name__ == '__main__':
main()
from abc import ABCMeta, abstractmethod
class Pet(object, metaclass=ABCMeta):
""" """
def __init__(self, nickname):
self._nickname = nickname
@abstractmethod
def make_voice(self):
""" """
pass
class Dog(Pet):
""" """
def make_voice(self):
print('%s: ...' % self._nickname)
class Cat(Pet):
""" """
def make_voice(self):
print('%s: ... ...' % self._nickname)
def main():
pets = [Dog(' '), Cat(' '), Dog(' ')]
for pet in pets:
pet.make_voice()
if __name__ == '__main__':
main()
정수 비교
def main():
x = y = -1
while True:
x += 1
y += 1
if x is y:
print('%d is %d' % (x, y))
else:
print('Attention! %d is not %d' % (x, y))
break
x = y = 0
while True:
x -= 1
y -= 1
if x is y:
print('%d is %d' % (x, y))
else:
print('Attention! %d is not %d' % (x, y))
break
if __name__ == '__main__':
main()
import dis
a = 257
def main():
b = 257 # 6
c = 257 # 7
print(b is c) # True
print(a is b) # False
print(a is c) # False
if __name__ == "__main__":
main()
새 겨 진 목록
def main():
names = [' ', ' ', ' ', ' ', ' ']
subjs = [' ', ' ', ' ']
scores = [[0] * 3] * 5
for row, name in enumerate(names):
print(' %s ' % name)
for col, subj in enumerate(subjs):
scores[row][col] = float(input(subj + ': '))
print(scores)
if __name__ == '__main__':
main()
a = object()
b = ['apple', 'pitaya', 'grape']
def main():
names = [' ', ' ', ' ', ' ', ' ']
subjs = [' ', ' ', ' ']
scores = [[]] * 5 # scores = [[0] * 3 for _ in range(5)]
for row, name in enumerate(names):
print(' %s ' % name)
scores[row] = [0] * 3
for col, subj in enumerate(subjs):
scores[row][col] = float(input(subj + ': '))
print(scores)
if __name__ == '__main__':
main()
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 함수의 귀속함수는 코드의 봉인으로 다른 프로그램에 호출될 수도 있고 함수 내부에서 호출될 수도 있으며 함수 내부에서 자신을 호출하는 방식을 함수의 귀속이라고 부른다.마치 사람이 거울 앞에 서서 거울을 보는 것과 같다. 한 사람...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.