2020-12-10
  • |
  • daafoor
  • |
  • مشاهدات: 2046

فيما يلي امثلة على الاصناف / الفئات / الكلاسات  في لغة بايثون

وايضا امثلة توضح الفرق بين class و object

مثال على انشاء كلاس في بايثون:

# Python program to 
# demonstrate instantiating 
# a class 

class Dog:
	attr1 = "mamal"
	attr2 = "dog"

	# A sample method 
	def fun(self): 
		print("I'm a", self.attr1) 
		print("I'm a", self.attr2) 

# Driver code 
# Object instantiation 
Rodger = Dog() 

# Accessing class attributes 
# and method through objects 
print(Rodger.attr1) 
Rodger.fun() 

المخرجات:

mamal
I'm a mamal
I'm a dog

 

 

مثال على تعريف تابع الباني constructor في صنف:

وطبعا تابع الباني هو حالة خاصة من التوابع, مسؤول عن انشاء instance من class

# A Sample class with init method 
class Person: 
	
	# init method or constructor 
	def __init__(self, name): 
		self.name = name 
	
	# Sample Method 
	def say_hi(self): 
		print('Hello, my name is', self.name) 
	
p = Person('Nikhil') 
p.say_hi() 

المخرجات:

Hello, my name is Nikhil

 

 

مثال على class and instance باستخدام البايثون:

# Python program to show that the variables with a value 
# assigned in the class declaration, are class variables and 
# variables inside methods and constructors are instance 
# variables. 
	
# Class for Dog 
class Dog: 
	
	# Class Variable 
	animal = 'dog'			
	
	# The init method or constructor 
	def __init__(self, breed, color): 
	
		# Instance Variable	 
		self.breed = breed 
		self.color = color		 
	
# Objects of Dog class 
Rodger = Dog("Pug", "brown") 
Buzo = Dog("Bulldog", "black") 

print('Rodger details:') 
print('Rodger is a', Rodger.animal) 
print('Breed: ', Rodger.breed) 
print('Color: ', Rodger.color) 

print('\nBuzo details:') 
print('Buzo is a', Buzo.animal) 
print('Breed: ', Buzo.breed) 
print('Color: ', Buzo.color) 

# Class variables can be accessed using class 
# name also 
print("\nAccessing class variable using class name") 
print(Dog.animal)		 

المخرجات:

Rodger details:
Rodger is a dog
Breed:  Pug
Color:  brown

Buzo details:
Buzo is a dog
Breed:  Bulldog
Color:  black

Accessing class variable using class name
dog

 

 

 

ابحث عن مسائل برمجة بايثون | Python programming بالانجليزي

هل أعجبك المحتوى؟

محتاج مساعدة؟ تواصل مع مدرس اونلاين الان!

التعليقات
لا يوجد تعليقات
لاضافة سؤال او تعليق على المشاركة يتوجب عليك تسجيل الدخول
تسجيل الدخول