파이썬, 객체 생성
나는 파이썬을 배우려고 노력하고 있으며 지금은 수업을 중단시키고 인스턴스로 클래스를 조작하는 방법을 찾으려고 노력하고 있습니다.
이 연습 문제를 이해하지 못하는 것 같습니다.
이름, 나이 및 전공이 입력과 동일한 학생 객체를 만들어 반환
def make_student(name, age, major)
객체에 의해 의미하는 바를 얻지 못합니다.이 값을 보유하는 함수 내에 배열을 만들어야한다는 의미입니까? 또는 클래스를 만들고이 함수를 내부에 배치하고 인스턴스를 할당합니까? (이 질문 전에 나는 이름, 나이 및 전공을 가진 학생 클래스를 설정하도록 요청 받았다)
class Student:
name = "Unknown name"
age = 0
major = "Unknown major"
class Student(object):
name = ""
age = 0
major = ""
# The class "constructor" - It's actually an initializer
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def make_student(name, age, major):
student = Student(name, age, major)
return student
파이썬 철학의 원칙 중 하나가 "하나의 명백한 방법이 있어야한다" 는 것이지만 , 이를 수행하는 방법은 여전히 여러 가지가 있습니다. 다음 두 코드 조각을 사용하여 Python의 동적 기능을 활용할 수도 있습니다.
class Student(object):
name = ""
age = 0
major = ""
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
# Note: I didn't need to create a variable in the class definition before doing this.
student.gpa = float(4.0)
return student
전자를 선호하지만 후자가 유용 할 수있는 인스턴스가 있습니다. 하나는 MongoDB와 같은 문서 데이터베이스로 작업 할 때 유용합니다.
클래스를 작성하고 메소드를 제공하십시오 __init__
.
class Student:
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
def is_old(self):
return self.age > 100
이제 Student
클래스 의 인스턴스를 초기화 할 수 있습니다 :
>>> s = Student('John', 88, None)
>>> s.name
'John'
>>> s.age
88
make_student
와 같은 일을하는 경우 왜 학생 기능 이 필요한지 잘 모르겠습니다 Student.__init__
.
객체는 클래스의 인스턴스입니다. 클래스는 단지 객체의 청사진입니다. 클래스 정의가 주어지면-
# Note the added (object) - this is the preferred way of creating new classes
class Student(object):
name = "Unknown name"
age = 0
major = "Unknown major"
You can create a make_student
function by explicitly assigning the attributes to a new instance of Student
-
def make_student(name, age, major):
student = Student()
student.name = name
student.age = age
student.major = major
return student
But it probably makes more sense to do this in a constructor (__init__
) -
class Student(object):
def __init__(self, name="Unknown name", age=0, major="Unknown major"):
self.name = name
self.age = age
self.major = major
The constructor is called when you use Student()
. It will take the arguments defined in the __init__
method. The constructor signature would now essentially be Student(name, age, major)
.
If you use that, then a make_student
function is trivial (and superfluous) -
def make_student(name, age, major):
return Student(name, age, major)
For fun, here is an example of how to create a make_student
function without defining a class. Please do not try this at home.
def make_student(name, age, major):
return type('Student', (object,),
{'name': name, 'age': age, 'major': major})()
when you create an object using predefine class, at first you want to create a variable for storing that object. Then you can create object and store variable that you created.
class Student:
def __init__(self):
# creating an object....
student1=Student()
Actually this init method is the constructor of class.you can initialize that method using some attributes.. In that point , when you creating an object , you will have to pass some values for particular attributes..
class Student:
def __init__(self,name,age):
self.name=value
self.age=value
# creating an object.......
student2=Student("smith",25)
참고URL : https://stackoverflow.com/questions/15081542/python-creating-objects
'IT박스' 카테고리의 다른 글
예외를 발생시키는 람다 식 정의 (0) | 2020.07.18 |
---|---|
해당 속성의 이름에 해당하는 문자열이 주어진 객체 속성에 액세스하는 방법 (0) | 2020.07.18 |
(object) 0 == (object) 0이 ((object) 0) .Equals ((object) 0)과 다른 이유는 무엇입니까? (0) | 2020.07.18 |
ORA-30926 : 소스 테이블에 안정적인 행 세트를 취득 할 수 없습니다 (0) | 2020.07.18 |
Android 화면 크기 HDPI, LDPI, MDPI (0) | 2020.07.18 |